import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/core/utils/log_util.dart';
import 'package:enterprise_v6_app/app/data/entities/common/department_tree_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/common/department_user_entity.dart';
import 'package:get/get.dart';

class PersonnelDepartmentTreeController extends GetxController {
  /// 页面标题
  String title = '';

  /// 模块类型：1：后台 2：特殊作业 3：双重预防机制 4：重大危险源 5：敏捷应急 6：安全教育培训 7：通用 8：智慧仓库 9：安全基础管理 10：封闭化 11：标准化 12：清单制
  String type = '1';

  /// 组织数据
  List<DepartmentTreeEntity> departmentTreeList = [];

  /// 是否为单选
  bool isRadio = true;

  /// 当前选中的人员数据
  List<DepartmentUserEntity> selectedUserList = [];

  /// 查询组织接口
  String? organizationalInterface;

  /// 查询人员接口
  String? personnelInterface;

  @override
  void onInit() {
    super.onInit();
    final Map<String, dynamic> arguments = Get.arguments as Map<String, dynamic>;
    try {
      // 获取标题
      title = arguments['title'] as String;
      // 获取类型
      type = arguments['type'] as String;
      if (arguments['isRadio'] != null) {
        // 是否单选
        isRadio = arguments['isRadio'] as bool;
      }
      if (arguments['organizationalInterface'] != null && arguments['organizationalInterface'] is String) {
        // 查询组织接口
        organizationalInterface = arguments['organizationalInterface'] as String;
      }
      if (arguments['personnelInterface'] != null && arguments['personnelInterface'] is String) {
        // 查询人员接口
        personnelInterface = arguments['personnelInterface'] as String;
      }
    } catch (e) {
      AppLogger.printLog(e.toString());
    }
    // 初始化数据
    initData();
  }

  Future<void> initData() async {
    //获取所有组织数据
    final res = await HttpUtil()
        .generateGetRequest<List<DepartmentTreeEntity>>(organizationalInterface ?? Interface.getDepartmentTree, queryParameters: {'type': type}).execute();
    res.onSuccess((result) {
      if (result.data != null && result.data!.isNotEmpty) {
        departmentTreeList = result.data!;
      }
      update();
    });
  }

  /// 点击组织节点
  Future<void> clickOnNode(DepartmentTreeEntity treeEntity) async {
    treeEntity.isExpand = !treeEntity.isExpand!;
    // 展开状态且节点人员为空调用接口查询人员
    if (treeEntity.isExpand! && treeEntity.userList!.isEmpty) {
      final userList = await getUserByTypeAndBDepart(treeEntity);
      treeEntity.userList!.addAll(userList);
      update();
    } else {
      update();
    }
  }

  /// 获取组织人员
  Future<List<DepartmentUserEntity>> getUserByTypeAndBDepart(DepartmentTreeEntity treeEntity) async {
    final List<DepartmentUserEntity> userList = [];
    //获取组织人员数据
    final res = await HttpUtil().generatePostRequest<List<DepartmentUserEntity>>(
      personnelInterface ?? Interface.getUserByAdministrationList,
      data: {
        'ids': ['${treeEntity.id}'],
        'type': type,
        'isAll': '2',
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data != null && result.data!.isNotEmpty) {
        userList.addAll(result.data!);
      }
    });
    return userList;
  }

  /// 点击选择人员
  void selectPersonnel(DepartmentUserEntity user) {
    // 单选
    if (isRadio) {
      selectedUserList.clear();
      selectedUserList.add(user);
    } else {
      // 不包含相同id
      if (!selectedUserList.any((object) => object.id == user.id)) {
        selectedUserList.add(user);
      } else {
        selectedUserList.remove(user);
      }
    }
    update();
  }

  /// 判断人员是否选中
  /// 返回 ture: 选中
  bool userIsSelected(DepartmentUserEntity user) {
    if (selectedUserList.any((object) => object.id == user.id)) {
      return true;
    }
    return false;
  }

  /// 完成
  void complete() {
    if (selectedUserList.isEmpty) {
      AppToast.showWarning('请选择人员!');
      return;
    }
    Get.back(result: selectedUserList);
  }
}
